﻿namespace Vdc.Grid
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Reflection;
    using System.Threading;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    [ToolboxItem(false)]
    public class DetailGrid : Vdc.Grid.Grid, ICloneable
    {
        internal List<DetailGrid> ConcreteInstances = new List<DetailGrid>();
        internal bool IsClone;
        internal Vdc.Grid.Grid MasterGrid;
        internal GridRow MasterRow;
        internal string SourceGridID;

        public event Vdc.Grid.Grid.EventHandler DeleteCommand;

        public event Vdc.Grid.Grid.EventHandler InsertCommand;

        public event Vdc.Grid.Grid.DefaultEventHandler Rebind;

        public event Vdc.Grid.Grid.EventHandler Select;

        public event Vdc.Grid.Grid.EventHandler UpdateCommand;

        internal void CallCreateChildControls()
        {
        }

        public object Clone()
        {
            DetailGrid grid = new DetailGrid {
                IsClone = true,
                AllowAddingRecords = base.AllowAddingRecords,
                AllowColumnResizing = base.AllowColumnResizing,
                AllowDataAccessOnServer = base.AllowDataAccessOnServer,
                AllowFiltering = base.AllowFiltering,
                AllowGrouping = base.AllowGrouping,
                AllowKeyNavigation = base.AllowKeyNavigation,
                AllowManualPaging = base.AllowManualPaging,
                AllowMultiRecordAdding = base.AllowMultiRecordAdding,
                AllowMultiRecordDeleting = base.AllowMultiRecordDeleting,
                AllowMultiRecordEditing = base.AllowMultiRecordEditing,
                AllowMultiRecordSelection = base.AllowMultiRecordSelection,
                AllowPageSizeSelection = base.AllowPageSizeSelection,
                AllowPaging = base.AllowPaging,
                AllowRecordSelection = base.AllowRecordSelection,
                AllowSorting = base.AllowSorting,
                AutoGenerateColumns = base.AutoGenerateColumns,
                AutoPostBackOnSelect = base.AutoPostBackOnSelect,
                CallbackMode = base.CallbackMode,
                CurrentPageIndex = base.CurrentPageIndex,
                EmbedFilterInSortExpression = base.EmbedFilterInSortExpression,
                EnableRecordHover = base.EnableRecordHover,
                EnableTypeValidation = base.EnableTypeValidation,
                FilterType = base.FilterType,
                FolderExports = base.FolderExports,
                FolderLocalization = base.FolderLocalization,
                FolderStyle = base.FolderStyle,
                ForeignKeys = this.ForeignKeys,
                GenerateRecordIds = base.GenerateRecordIds,
                GroupBy = base.GroupBy,
                HideColumnsWhenGrouping = base.HideColumnsWhenGrouping,
                KeepSelectedRecords = base.KeepSelectedRecords,
                Language = base.Language,
                NumberOfPagesShownInFooter = base.NumberOfPagesShownInFooter,
                PageSize = base.PageSize,
                PageSizeOptions = base.PageSizeOptions,
                Serialize = base.Serialize,
                ShowCollapsedGroups = base.ShowCollapsedGroups,
                ShowColumnsFooter = base.ShowColumnsFooter,
                ShowFooter = base.ShowFooter,
                ShowGroupFooter = base.ShowGroupFooter,
                ShowGroupsInfo = base.ShowGroupsInfo,
                ShowHeader = base.ShowHeader,
                ShowLoadingMessage = base.ShowLoadingMessage,
                ShowMultiPageGroupsInfo = base.ShowMultiPageGroupsInfo,
                ShowTooltipOnResize = base.ShowTooltipOnResize,
                ShowTotalNumberOfPages = base.ShowTotalNumberOfPages,
                Visible = this.Visible,
                Width = this.Width,
                DataSourceID = this.DataSourceID
            };
            if (string.IsNullOrEmpty(this.DataSourceID))
            {
                grid.preventPreviousDataSourceClearing = true;
                grid.DataSource = this.ExtractDetailDataSource();
                grid.preventPreviousDataSourceClearing = false;
            }
            grid.AddEditDeleteSettings = base.AddEditDeleteSettings.Clone() as GridAddEditDeleteSettings;
            grid.ClientSideEvents = base.ClientSideEvents.Clone() as GridClientSideEvents;
            grid.CssSettings = base.CssSettings.Clone() as GridCssSettings;
            grid.LocalizationSettings = base.LocalizationSettings.Clone() as GridLocalizationSettings;
            grid.ExportingSettings = base.ExportingSettings.Clone() as GridExportingSettings;
            grid.FilteringSettings = base.FilteringSettings.Clone() as GridFilteringSettings;
            grid.PagingSettings = base.PagingSettings.Clone() as GridPagingSettings;
            grid.ScrollingSettings = base.ScrollingSettings.Clone() as GridScrollingSettings;
            foreach (GridTemplate template in base.Templates)
            {
                if (template is GridRuntimeTemplate)
                {
                    GridRuntimeTemplate oGridTemplate = template.Clone() as GridRuntimeTemplate;
                    oGridTemplate.ID = template.ID;
                    grid.Templates.Add(oGridTemplate);
                }
                else
                {
                    GridTemplate template3 = template.Clone() as GridTemplate;
                    template3.ID = template.ID;
                    grid.Templates.Add(template3);
                }
            }
            grid.TemplateSettings = base.TemplateSettings.Clone() as GridTemplateSettings;
            if (this.Rebind != null)
            {
                grid.Rebind += this.Rebind;
            }
            if (this.InsertCommand != null)
            {
                grid.InsertCommand += this.InsertCommand;
            }
            if (this.UpdateCommand != null)
            {
                grid.UpdateCommand += this.UpdateCommand;
            }
            if (this.DeleteCommand != null)
            {
                grid.DeleteCommand += this.DeleteCommand;
            }
            if (this.Select != null)
            {
                grid.Select += this.Select;
            }
            if (base.Events[Vdc.Grid.Grid.RowCreatedKey] != null)
            {
                grid.RowCreated += (base.Events[Vdc.Grid.Grid.RowCreatedKey] as GridRowEventHandler);
            }
            if (base.Events[Vdc.Grid.Grid.RowDataBoundKey] != null)
            {
                grid.RowDataBound += (base.Events[Vdc.Grid.Grid.RowDataBoundKey] as GridRowEventHandler);
            }
            if (base.Events[Vdc.Grid.Grid.ColumnsCreatedKey] != null)
            {
                grid.ColumnsCreated += (base.Events[Vdc.Grid.Grid.ColumnsCreatedKey] as Vdc.Grid.Grid.DefaultEventHandler);
            }
            if (base.Events[Vdc.Grid.Grid.DataSourceNeededKey] != null)
            {
                grid.DataSourceNeeded += (base.Events[Vdc.Grid.Grid.DataSourceNeededKey] as GridDataSourceNeededEventHandler);
            }
            if (base.Events[Vdc.Grid.Grid.FilteringKey] != null)
            {
                grid.Filtering += (base.Events[Vdc.Grid.Grid.FilteringKey] as System.EventHandler);
            }
            if (base.Events[Vdc.Grid.Grid.TemplatesCreatedKey] != null)
            {
                grid.TemplatesCreated += (base.Events[Vdc.Grid.Grid.TemplatesCreatedKey] as System.EventHandler);
            }
            foreach (Column column in base.Columns)
            {
                Column oCol = null;
                if ((column is CheckBoxColumn) || (column is CheckBoxSelectColumn))
                {
                    if (column is CheckBoxColumn)
                    {
                        oCol = (column as CheckBoxColumn).Clone() as CheckBoxColumn;
                    }
                    else
                    {
                        oCol = (column as CheckBoxSelectColumn).Clone() as CheckBoxSelectColumn;
                    }
                }
                else
                {
                    oCol = column.Clone() as Column;
                }
                grid.Columns.Add(oCol);
            }
            foreach (DetailGrid grid2 in base.DetailGrids)
            {
                grid.DetailGrids.Add(grid2);
            }
            grid.CopyUnchangeableProperties(this);
            this.GetRootMasterGrid();
            string str = this.MasterRow.DataItemIndex.ToString();
            for (Vdc.Grid.Grid grid3 = this.MasterGrid; grid3 is DetailGrid; grid3 = (grid3 as DetailGrid).MasterGrid)
            {
                str = str + "_" + (grid3 as DetailGrid).MasterRow.DataItemIndex.ToString();
            }
            grid.ID = this.ID + "_" + str;
            grid.SourceGridID = this.ID;
            return grid;
        }

        internal virtual void CopyUnchangeableProperties(DetailGrid sourceGrid)
        {
            base.MasterDetailSettings.LoadingMode = sourceGrid.MasterDetailSettings.LoadingMode;
            base.MasterDetailSettings.State = sourceGrid.MasterDetailSettings.State;
            base.MasterDetailSettings.ShowEmptyDetails = sourceGrid.MasterDetailSettings.ShowEmptyDetails;
            base.MasterDetailSettings.DetailsCountField = sourceGrid.MasterDetailSettings.DetailsCountField;
        }

        protected override DataSourceSelectArguments CreateDataSourceSelectArguments()
        {
            this.SetDataSourceParameters();
            return base.CreateDataSourceSelectArguments();
        }

        public override void DataBind()
        {
            if (!string.IsNullOrEmpty(this.DataSourceID))
            {
                this.SetDataSourceParameters();
            }
            if (this.DataSource is IDataReader)
            {
                base.internalDataSource = base.ConvertIDataReaderToIEnumerable(this.DataSource as IDataReader);
            }
            else if (((this.DataSource is IEnumerable) && !(this.DataSource is DataView)) && (this.DataSource is ICollection))
            {
                base.internalDataSource = base.ConvertICollectionToDataView(this.DataSource as ICollection);
            }
            else if (this.DataSource is IEnumerable)
            {
                base.internalDataSource = this.DataSource as IEnumerable;
            }
            if (this.MasterRow != null)
            {
                base.DataBind();
                if (string.IsNullOrEmpty(this.DataSourceID))
                {
                    foreach (DetailGrid grid in this.ConcreteInstances)
                    {
                        grid.preventPreviousDataSourceClearing = true;
                        grid.DataSource = this.ExtractDetailDataSource();
                        grid.preventPreviousDataSourceClearing = false;
                        grid.DataBind();
                    }
                }
            }
        }

        private IEnumerable ExtractDetailDataSource()
        {
            Hashtable hashtable = this.MasterRow.ToHashtable();
            string[] strArray = this.ForeignKeys.Split(new char[] { ',' });
            ArrayList list = new ArrayList();
            if ((base.internalDataSource != null) && (hashtable.Count > 0))
            {
                foreach (object obj2 in base.internalDataSource)
                {
                    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj2);
                    bool flag = true;
                    foreach (PropertyDescriptor descriptor in properties)
                    {
                        foreach (string str in strArray)
                        {
                            if (!(descriptor.Name.ToLower() == str.ToLower()))
                            {
                                continue;
                            }
                            string str2 = string.Empty;
                            foreach (DictionaryEntry entry in hashtable)
                            {
                                if (entry.Key.ToString().ToLower() == str.ToLower())
                                {
                                    str2 = entry.Key.ToString();
                                    break;
                                }
                            }
                            if ((str2 != string.Empty) && (descriptor.GetValue(obj2).ToString() != hashtable[str2].ToString()))
                            {
                                flag = false;
                                break;
                            }
                        }
                        if (!flag)
                        {
                            break;
                        }
                    }
                    if (flag)
                    {
                        list.Add(obj2);
                    }
                }
            }
            if (base.internalDataSource != null)
            {
                return list;
            }
            return null;
        }

        protected override Vdc.Grid.Grid.EventHandler GetDeleteCommand()
        {
            return this.DeleteCommand;
        }

        protected override Dictionary<string, string> GetForeignKeysDictionary()
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(this.ForeignKeys))
            {
                string[] strArray = this.ForeignKeys.Split(new char[] { ',' });
                Hashtable hashtable = this.MasterRow.ToHashtable();
                foreach (string str in strArray)
                {
                    foreach (DictionaryEntry entry in hashtable)
                    {
                        if (entry.Key.ToString().ToLower() == str.ToLower())
                        {
                            string key = entry.Key.ToString();
                            dictionary.Add(key, entry.Value.ToString());
                            break;
                        }
                    }
                }
            }
            return dictionary;
        }

        protected override string GetForeignKeysValues()
        {
            string[] strArray = this.ForeignKeys.Split(new char[] { ',' });
            Hashtable hashtable = this.MasterRow.ToHashtable();
            string str = "{";
            bool flag = false;
            if (!string.IsNullOrEmpty(this.ForeignKeys))
            {
                foreach (string str2 in strArray)
                {
                    foreach (DictionaryEntry entry in hashtable)
                    {
                        if (entry.Key.ToString().ToLower() == str2.ToLower())
                        {
                            if (flag)
                            {
                                str = str + ",";
                            }
                            string str3 = str;
                            str = str3 + entry.Key.ToString() + ": {Value: '" + GridEncodingHelper.XMLCdataEncode(entry.Value.ToString().Replace("'", @"\'")) + "'}";
                            if (!flag)
                            {
                                flag = true;
                            }
                            break;
                        }
                    }
                }
            }
            return (str + "}");
        }

        protected override Vdc.Grid.Grid.EventHandler GetInsertCommand()
        {
            return this.InsertCommand;
        }

        internal override int GetLevelInHierarchy()
        {
            int num = 1;
            Vdc.Grid.Grid masterGrid = this.MasterGrid;
            while (masterGrid is DetailGrid)
            {
                masterGrid = ((DetailGrid) masterGrid).MasterGrid;
                num++;
            }
            return num;
        }

        protected override Vdc.Grid.Grid.DefaultEventHandler GetRebindEventHandler()
        {
            return this.Rebind;
        }

        internal override Vdc.Grid.Grid GetRootMasterGrid()
        {
            Vdc.Grid.Grid masterGrid = this.MasterGrid;
            while (masterGrid is DetailGrid)
            {
                masterGrid = ((DetailGrid) masterGrid).MasterGrid;
            }
            return masterGrid;
        }

        protected override Vdc.Grid.Grid.EventHandler GetSelectEventHandler()
        {
            return this.Select;
        }

        protected override Vdc.Grid.Grid.EventHandler GetUpdateCommand()
        {
            return this.UpdateCommand;
        }

        public override bool IsInCallbackHierarchy()
        {
            return (base.IsCallback || this.MasterGrid.IsInCallbackHierarchy());
        }

        protected override void MarkParentHierarchyAsReloadingBranch()
        {
            base.IsInsideReloadingBranch = true;
            for (Vdc.Grid.Grid grid = this.MasterGrid; grid != null; grid = ((DetailGrid) grid).MasterGrid)
            {
                grid.IsInsideReloadingBranch = true;
                if (!(grid is DetailGrid))
                {
                    break;
                }
            }
        }

        protected override void OnDataSourceViewChanged(object sender, EventArgs e)
        {
        }

        protected virtual void SetDataSourceParameters()
        {
            IDataSource dataSource = this.GetDataSource();
            Parameter parameter = null;
            Hashtable hashtable = this.MasterRow.ToHashtable();
            foreach (string str in this.ForeignKeys.Split(new char[] { ',' }))
            {
                if (dataSource is SqlDataSource)
                {
                    parameter = (dataSource as SqlDataSource).SelectParameters[str];
                }
                else if (dataSource is ObjectDataSource)
                {
                    parameter = (dataSource as ObjectDataSource).SelectParameters[str];
                }
                else if (dataSource.GetType().ToString() == "System.Web.UI.WebControls.LinqDataSource")
                {
                    ParameterCollection parameters = null;
                    parameters = dataSource.GetType().InvokeMember("WhereParameters", BindingFlags.GetProperty, null, dataSource, new object[0]) as ParameterCollection;
                    parameter = parameters[0];
                }
                if (parameter != null)
                {
                    foreach (DictionaryEntry entry in hashtable)
                    {
                        if (entry.Key.ToString().ToLower() == str.ToLower())
                        {
                            parameter.DefaultValue = entry.Value.ToString();
                            break;
                        }
                    }
                }
            }
        }

        object ICloneable.Clone()
        {
            return this.Clone();
        }

        [Description("Sets the expression for the Grouping feature."), Category("ForeignKeys"), DefaultValue(""), Bindable(true)]
        public string ForeignKeys
        {
            get
            {
                object obj2 = this.ViewState["ForeignKeys"];
                if (obj2 != null)
                {
                    return obj2.ToString();
                }
                return "";
            }
            set
            {
                this.ViewState["ForeignKeys"] = value;
            }
        }
    }
}

